package com.jinyijia.api.rest.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyijia.api.infrastructure.OrderManager;
import com.jinyijia.api.infrastructure.UserInfoManager;
import com.jinyijia.api.rest.v1.dto.*;
import com.jinyijia.api.rest.v1.vo.OrderSubmitDTO;
import com.jinyijia.api.rest.v1.vo.ShopInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lhw
 * @date 2018/8/8
 **/
@RestController
@RequestMapping("orders")
public class OrderController {

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 订单列表
     */
    @GetMapping
    public Map listOrders() {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("message", "OK");
        map.put("tabs", orderManager.tabs(UserInfoManager.getCurrentUserId()));
        return map;
    }

    /**
     * 订单详情
     */
    @GetMapping("{code}")
    public Object getOrder(@PathVariable String code) {
        return orderManager.orderDetail(code, UserInfoManager.getCurrentUserId());
    }

    /**
     * 订单提交
     *
     * @param submitDTO
     * @return
     * @author WX
     * @date 2018/8/21
     * update yangrd 10/09
     *
     */
    @PostMapping
    public ResponseEntity submitOrder(@RequestBody OrderSubmitDTO submitDTO) {
        Integer currentUserId = UserInfoManager.getCurrentUserId();
        String userCode = getUserCode(currentUserId.toString());
        String deliverWay = submitDTO.getDeliverWay();
        //将android前台传来的收货地址格式转化成后台需要的数据格式
        ShipAddressDTO address = getShipAddressDTO(submitDTO.getAddress());
        List<com.jinyijia.api.rest.v1.dto.OrderSubmitDTO> submitDTOS = new ArrayList<>();
        List<String> orderCodes = new ArrayList<>();
        try {
            List<ShopInfoVo> shopInfoVos = submitDTO.getList();
            //多个店铺
            shopInfoVos.forEach(shopInfoVo -> {
                com.jinyijia.api.rest.v1.dto.OrderSubmitDTO orderSubmitDTO = new com.jinyijia.api.rest.v1.dto.OrderSubmitDTO();
                //店铺信息
                orderSubmitDTO.setShopInfo(new ShopInfoDTO(shopInfoVo.getShopId(), shopInfoVo.getName(), ""));
                //用户信息
                orderSubmitDTO.setCustomInfo(new CustomInfoDTO(currentUserId.toString(), UserInfoManager.getCurrentUsername(), userCode));
                //地址信息
                orderSubmitDTO.setShipAddress(address);
                //配送方式
                orderSubmitDTO.setDeliverWay(deliverWay);

                //商品信息
                List<OrderItemDTO> items = new ArrayList<>();
                shopInfoVo.getCommodity().forEach(itemVo -> {
                    OrderItemDTO orderItemDTO = new OrderItemDTO(itemVo.getCount(), itemVo.getSkuId());
                    items.add(orderItemDTO);
                });
                orderSubmitDTO.setItems(items);
                submitDTOS.add(orderSubmitDTO);
            });
            restTemplate.setErrorHandler(new CustomResponseErrorHandler());
            ResponseEntity<JSONArray> responseEntity = restTemplate.postForEntity("http://order-service/orders", submitDTOS, JSONArray.class);
            //获取订单生成后返回数据里面的shopId和skuCode
            JSONArray ordersArray = responseEntity.getBody();
            for (int i = 0; i < ordersArray.size(); i++) {
                Map<String, Object> map = (Map<String, Object>) ordersArray.get(i);
                JSONObject o = new JSONObject(map);
                JSONArray items = o.getJSONArray("items");
                for (int j = 0; j < items.size(); j++) {
                    JSONObject item = (JSONObject) items.get(j);
                    JSONObject goodsInfo = item.getJSONObject("goodsInfo");
                    String skuCode = goodsInfo.getString("skuCode");
                    Integer shopId = goodsInfo.getJSONObject("shopInfo").getInteger("id");
                    //订单生成后根据(userId、shopId、skuCode)删除购物车信息
                    if(submitDTO.getOrigin().equals(OrderSubmitDTO.OriginEnum.SHOPPING_CART)){
                        restTemplate.delete("http://goods-service/carts?userId={1}&shopId={2}&skuCode={3}", currentUserId, shopId, skuCode);
                    }
                }
            }
            //  获取订单生成后的订单号
            List<Map<String, String>> orderDTOList = (List) responseEntity.getBody();
            for (Map<String, String> orderDto : orderDTOList) {
                orderCodes.add(orderDto.get("code"));
            }
        } catch (CustomException e) {
            Map<String, Object> map = JSON.parseObject(e.getBody(), Map.class);
            return ResponseEntity.ok(Result.error(map.get("message").toString()));
        }
        return ResponseEntity.ok(Result.success(orderCodes));
    }

    /**
     * 获取用户信息 code
     *
     * @param userId
     * @return
     * @author WX
     * @date 2018/8/21
     */
    private String getUserCode(String userId) {
        String userCode = "";
        try {
            UserDataDTO userDataDTO = restTemplate.getForObject("http://user-service/users/{1}", UserDataDTO.class, userId);
            userCode = userDataDTO.getUserCode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userCode;
    }

    //此方法为了将android前台页面传来的数据转化成后台需要的数据
    private ShipAddressDTO getShipAddressDTO(AndroidShipAddressDTO androidShipAddressDTO) {
        String[] address = androidShipAddressDTO.getRegion().split("-");
        return new ShipAddressDTO(androidShipAddressDTO.getId(), androidShipAddressDTO.getName(), androidShipAddressDTO.getPhone(), "中国", address[0], address[1], address[2], "", androidShipAddressDTO.getAddress(), androidShipAddressDTO.getEnabled());
    }
}
